<template>
    <el-steps class="mb-4" :space="200" :active="active" simple>
        <el-step title="组卷配置" :icon="EditPen" />
        <el-step title="考试权限" :icon="Lock" />
        <el-step title="补充配置" :icon="Setting" />
    </el-steps>
    <div style="margin-top: 12px">
        <el-button v-if="active > 0" @click="prev" size="large" style="float: left;">上一步</el-button>
        <el-button type="primary" v-if="active < 2" @click="next" size="large" class="rightButton">下一步</el-button>
        <el-button type="primary" v-else @click="submit" size="large" class="rightButton">&nbsp;提交&nbsp;</el-button>
    </div>

    <!-- 组卷配置 -->
    <div v-if="active == 0" style="margin-top: 70px;">
        <el-card>
            <el-radio-group v-model="radio1" @change="handleRadioChange">
                <el-radio value="1" size="large" border class="marginButton">题库组卷</el-radio>
                <el-radio value="2" size="large" border class="marginButton">自由组卷</el-radio>
            </el-radio-group>
            <span v-if="radio1 == '2'" style="float: right; color: red; font-weight: bold;">试卷总分:{{ examScores }}</span>
            <br>
            <div v-if="radio == 1">
                <el-button class="marginButton" @click="addBankRow"> + &nbsp;添加题库</el-button>
                <el-table :data="state.tableData1" style="width: 100%">
                    <el-table-column label="题库">
                        <template v-slot="scope">
                            <el-select size="large" v-model="scope.row.bankName" placeholder="选择题库">
                                <el-option v-for="bank in banks" :key="bank.bankId" :label="bank.bankName"
                                    :value="bank.bankName" />
                            </el-select>
                        </template>
                    </el-table-column>
                    <el-table-column label="单选题分数">
                        <template v-slot="scope">
                            <el-input size="large" v-model="scope.row.singleChoice" />
                        </template>
                    </el-table-column>
                    <el-table-column label="多选题分数">
                        <template v-slot="scope">
                            <el-input size="large" v-model="scope.row.multipleChoice" />
                        </template>
                    </el-table-column>
                    <el-table-column label="判断题分数">
                        <template v-slot="scope">
                            <el-input size="large" v-model="scope.row.judge" />
                        </template>
                    </el-table-column>
                    <el-table-column label="简答题分数">
                        <template v-slot="scope">
                            <el-input size="large" v-model="scope.row.shortAnswer" />
                        </template>
                    </el-table-column>
                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button type="danger" :icon="Delete" circle size="large"
                                @click="removeRow1(scope.$index)" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <div v-else>
                <el-card>
                    <h4>题目列表</h4>
                    <el-button style="margin: 15px 0;" type="primary" @click='fetchQuestions'> +
                        &nbsp;添加试题</el-button>
                </el-card>

                <el-table :data="state.tableData2" style="width: 100%">
                    <el-table-column label="序号" type="index" width="60px" />
                    <el-table-column prop="quContent" label="题目内容" />
                    <el-table-column prop="quType" label="题目类型">
                        <template v-slot="scope">
                            <span>{{ questionTypes[scope.row.quType] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="单题分数">
                        <template v-slot="scope">
                            <el-input size="large" v-model="scope.row.score" />
                        </template>
                    </el-table-column>

                    <el-table-column label="操作">
                        <template v-slot="scope">
                            <el-button type="danger" :icon="Delete" circle size="large"
                                @click="removeRow2(scope.$index)" />
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <el-dialog v-model="dialogTableVisible" title="添加题目" center style="width:80%"
                :before-close="handleDialogClose">
                <div style="margin-bottom: 20px;">
                    <el-select clearable v-model="state.questionType" placeholder="请选择题目类型"
                        style="width: 150px; margin-right: 10px;" size="large">
                        <el-option label="单选题" value="1"></el-option>
                        <el-option label="多选题" value="2"></el-option>
                        <el-option label="判断题" value="3"></el-option>
                        <el-option label="简答题" value="4"></el-option>
                    </el-select>
                    <el-select clearable v-model="state.questionBank" placeholder="请选择题库"
                        style="width: 150px; margin-right: 10px;" size="large">
                        <el-option v-for="bank in banks" :key="bank.bankId" :label="bank.bankName"
                            :value="bank.bankName" />
                    </el-select>
                    <el-input v-model="state.questionContent" placeholder="题目内容"
                        style="width: 200px; margin-right: 10px;" @blur="fetchQuestions" @keyup.enter="fetchQuestions"
                        size="large" />
                    <el-button type="primary" size="large" style="float: right;" @click="confirmSelection">{{ confirm
                        }}</el-button>
                </div>
                <el-table :data="state.questionData" border style="width: 100%" header-background="#f2f3f4"
                    @selection-change="handleSelectionChange" tooltip-effect="dark">
                    <el-table-column type="selection" width="60" />
                    <el-table-column prop="quType" label="题目类型">
                        <template v-slot="scope">
                            <span>{{ questionTypes[scope.row.quType] }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="quContent" label="题目内容" />
                    <el-table-column prop="level" label="难度">
                        <template v-slot="scope">
                            <span>{{ difficultyLevels[scope.row.level] }}</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="quBankName" label="所属题库" />
                    <el-table-column prop="createPerson" label="创建人" />
                    <el-table-column prop="createTime" label="创建时间" />
                </el-table>

                <!-- 分页查询 -->
                <div class="demo-pagination-block">
                    <div class="demonstration"></div>
                    <el-pagination v-model:current-page="state.pageNo" v-model:page-size="state.pageSize"
                        :page-sizes="[5, 10, 15, 20]" :page-size="size" :disabled="disabled" :background="background"
                        layout="total, sizes, prev, pager, next, jumper" :total="state.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-dialog>
        </el-card>
    </div>

    <!-- 考试权限 -->
    <div v-else-if="active == 1" style="margin-top: 70px;">
        <el-card>
            <el-radio-group v-model="radio2">
                <el-radio value="1" size="large" border class="marginButton">完全公开</el-radio>
                <el-radio value="2" size="large" border class="marginButton">需要密码</el-radio>
            </el-radio-group>
            <div v-if="radio2 == '1'">
                <el-alert v-if="showAlert" title="完全公开，任何人都可以进行考试！" type="warning" @close="showAlert = false" />
            </div>
            <div v-if="radio2 == '2'">
                <el-alert v-if="showAlert" title="需要密码，知道密码的人员才可以考试！" type="warning" @close="showAlert = false" />
                <el-input v-model="examPassword" style="width: 240px ;margin-top: 20px;" type="password"
                    placeholder="请输入密码" show-password size="large" />
            </div>
        </el-card>
    </div>



    <!-- 补充配置 -->
    <div v-else style="margin-top: 70px;">
        <el-card>
            <el-form :model="additionalConfig" :rules="rules" ref="form" label-width="120px">
                <el-form-item label="考试名称" prop="examName" required>
                    <el-input v-model="additionalConfig.examName" placeholder="请输入考试名称" size="large" />
                </el-form-item>
                <el-form-item label="考试描述">
                    <el-input v-model="additionalConfig.examDescription" placeholder="请输入考试描述" size="large" />
                </el-form-item>
                <el-form-item v-if="radio1 == '2'" label="总分数" prop="examScores">
                    <el-input-number v-model="examScores" :disabled="true" size="large" />
                </el-form-item>
                <el-form-item label="及格分数" prop="passingScore" required>
                    <el-input-number v-model="additionalConfig.passingScore" :min="1" size="large" />
                </el-form-item>
                <el-form-item label="考试时长(分钟)" prop="examDuration" required>
                    <el-input-number v-model="additionalConfig.examDuration" :min="1" size="large" />
                </el-form-item>
                <el-form-item label="考试开始时间">
                    <el-date-picker v-model="additionalConfig.startTime" type="date" placeholder="考试开始时间"
                        size="large" />
                </el-form-item>
                <el-form-item label="考试结束时间">
                    <el-date-picker v-model="additionalConfig.endTime" type="date" placeholder="考试结束时间" size="large" />
                </el-form-item>
            </el-form>
        </el-card>
    </div>


</template>

<script setup lang="ts">
import { EditPen, Lock, Setting, CirclePlus, Delete } from '@element-plus/icons-vue'
import { ElMessageBox } from 'element-plus'
import { ref, reactive, inject, onMounted, watch, computed } from 'vue'
import { log } from 'console';
import { useRouter } from 'vue-router';
const router = useRouter()
const confirm = ref('确认0项')
const dialogTableVisible = ref(false)
import {
    getBankQuestionSum,
    getFetchQuestions,
    addExamByBank,
    addExamByQuestionList,
} from '@/api/examControl/AddExam'
const active = ref(0)
// 组卷配置
const radio = ref('1')
const radio1 = ref('1')
// 考试权限
const radio2 = ref('1')
// 是否显示Alert 提示
const showAlert = ref(true)
const examPassword = ref('')
const banks = ref([])
const state = reactive({
    tableData1: [],
    tableData2: [],
    selectedRows: [],
    questionData: [],
    questionType: '',
    questionBank: '',
    questionContent: '',
    pageNo: 1,
    pageSize: 10,
    total: 0
})

const examScores = computed(() => {
    return state.tableData2.reduce((total, item) => {
        const score = parseFloat(item.score);
        return total + (isNaN(score) ? 0 : score);
    }, 0);
});

// 补充配置
const form = ref(null);
const additionalConfig = reactive({
    examName: '',
    examDescription: '',
    passingScore: 1,
    examDuration: 1,
    startTime: '',
    endTime: ''
});
const rules = reactive({
    examName: [
        { required: true, message: '请输入考试名称', trigger: 'blur' }
    ],
    passingScore: [
        { required: true, message: '请输入通过分数', trigger: 'blur' }
    ],
    examDuration: [
        { required: true, message: '请输入考试时长', trigger: 'blur' }
    ]
});

const validateForm = () => {
    form.value.validate((valid) => {
        if (valid) {
            // 表单验证通过
        } else {
            // 表单验证未通过
            return false;
        }
    });
};
// 题型
const questionTypes = {
    1: '单选题',
    2: '多选题',
    3: '判断题',
    4: '简答题'
}
// 难易程度
const difficultyLevels = {
    1: '简单',
    2: '中等',
    3: '困难'
}
const next = () => {
    if (active.value < 2) {
        active.value++
    }
}
const prev = () => {
    if (active.value > 0) {
        active.value--
    }
}


// 监听的变化
watch(() => [state.questionType, state.questionBank], () => {
    fetchQuestions();
});
onMounted(() => {
    getBankHaveQuestionSums();
});

const handleDialogClose = (done) => {
    state.pageNo = 1
    state.pageSize = 10
    state.questionType = '';
    state.questionBank = '';
    state.questionContent = '';
    done();
};

async function getBankHaveQuestionSums() {
    try {
        const response = await getBankQuestionSum();
        console.log(response);
        
        banks.value = response.data.data.bankHaveQuestionSums.map((item: any) => ({
            bankId: item.questionBank.bankId,
            bankName: item.questionBank.bankName
        }))
    } catch (error) {
        console.error('获取题库数据失败', error)
    }
}

const handleRadioChange = async (value: string) => {
    ElMessageBox.confirm(
        '此操作将丢失当前组卷数据, 是否继续?',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            // 清空当前组卷数据
            state.tableData1 = [];
            state.tableData2 = [];
            radio.value = value;
        })
        .catch(() => {
            // 保持原来的值
            radio.value = (value == '1' ? '2' : '1');
            radio1.value = (value == '1' ? '2' : '1');
        });
}


const addBankRow = () => {
    state.tableData1.push({
        bankName: '',
        singleChoice: 1,
        multipleChoice: 1,
        judge: 1,
        shortAnswer: 1
    })
}

const removeRow1 = (index: number) => {
    state.tableData1.splice(index, 1)
}
const removeRow2 = (index: number) => {
    state.tableData2.splice(index, 1)
}

const fetchQuestions = async () => {
    try {
        state.questionType = state.questionType || '';
        state.questionBank = state.questionBank || '';
        state.questionContent = state.questionContent || '';
        const  {data}  = await getFetchQuestions(state.questionType,state.questionBank,state.questionContent,state.pageNo,state.pageSize);
        state.questionData = data.data.questions;
        state.total = data.data.total;
        dialogTableVisible.value = true;
    } catch (error) {
        console.error('获取试题数据失败', error)
    }
}
// 处理选中行变化的函数
const handleSelectionChange = (selectedRows: any[]) => {
    state.selectedRows = selectedRows;
    console.dir(state.selectedRows)
    confirm.value = `确认${selectedRows.length}项`;
};

const confirmSelection = () => {
    state.tableData2.push(...state.selectedRows.map(row => ({
        quId: row.id,
        quContent: row.quContent,
        quType: row.quType,
        score: '1'
    })));
    dialogTableVisible.value = false;
};

// 分页大小变化和当前页变化的事件处理函数
const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`);
    state.pageSize = val;
    fetchQuestions();
};

const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`);
    state.pageNo = val;
    fetchQuestions();
};
// 提交
const submit = async () => {
    try {
        let response;
        const commonParams = {
            startTime: additionalConfig.startTime,
            endTime: additionalConfig.endTime,
            examName: additionalConfig.examName,
            examDesc: additionalConfig.examDescription,
            examDuration: additionalConfig.examDuration,
            passScore: additionalConfig.passingScore,
            status: 1,
            type: radio2.value,
            examId: "",
            password: examPassword.value
        };
        if (radio1.value === '1') {
            // 题库组卷
            const bankNames = state.tableData1.map(item => item.bankId).join(',');
            const params = {
                ...commonParams,
                bankNames,
                singleScore: state.tableData1[0].singleChoice,
                multipleScore: state.tableData1[0].multipleChoice,
                judgeScore: state.tableData1[0].judge,
                shortScore: state.tableData1[0].shortAnswer,
            };
            response = await addExamByBank(params);
        } else {
            // 自由组卷
            const questionIds = state.tableData2.map(item => item.quId).join(',');
            const scores = state.tableData2.map(item => item.score).join(',');
            const params = {
                ...commonParams,
                questionIds,
                scores,
                totalScore: examScores.value,
            };
            response = await addExamByQuestionList(params);
        }
        if (response.data.status == 200) {
            // 提交成功
            console.log("提交成功");
        } else {
            // 提交失败
            console.log("提交失败");
        }
    } catch (error) {
        console.error('提交失败', error);
    }
    router.push({ path: `/home/examManage` });
};

</script>

<style scoped>
.rightButton
{
    float: right;
}

.marginButton
{
    margin: 5px 20px 15px 0;
}
</style>
